﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;

namespace ErikLieben.SharePoint.WebParts
{
    public partial class FaceBookWebPartSettings : System.Web.UI.Page
    {
        #region [ Fields ]

        protected CheckBoxList chklstUsersInFaceBook;
        protected Button btnModify;

        #endregion

        protected override void OnInit(EventArgs e)
        {
            btnModify.Click += new EventHandler(BtnModify_Click);
            base.OnInit(e);
        }

        private void BtnModify_Click(object sender, EventArgs e)
        {
            using (SPSite site = SPContext.Current.Site)
            {
                UserProfileManager profileManager = new UserProfileManager(ServerContext.Current);
                foreach (ListItem item in chklstUsersInFaceBook.Items)
                {
                    UserProfile userProfile = profileManager.GetUserProfile(new Guid(item.Value));
                    userProfile["VisibleInFaceBook"].Value = item.Selected;
                    userProfile.Commit();
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack) return;

            using (SPSite site = SPContext.Current.Site)
            {
                UserProfileManager profileManager = new UserProfileManager(ServerContext.Current);
                foreach (UserProfile profile in profileManager)
                {
                    var propertyPreferredName = profile["PreferredName"];
                    var propertyVisibleInFaceBook = profile["VisibleInFaceBook"];
                    if (propertyPreferredName != null)
                    {
                        if (propertyPreferredName.Value != null)
                            if (propertyVisibleInFaceBook != null && propertyVisibleInFaceBook.Value != null)
                            {
                                ListItem item = new ListItem(propertyPreferredName.Value.ToString(), profile.ID.ToString());
                                item.Selected = Boolean.Parse(propertyVisibleInFaceBook.Value.ToString());
                                chklstUsersInFaceBook.Items.Add(item);
                            }
                            else
                                chklstUsersInFaceBook.Items.Add(new ListItem(propertyPreferredName.Value.ToString()));

                    }
                }
            }
        }
    }
}
